package com.mxdx.edu.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.mxdx.base.service.facade.IFileUploadServiceFacade;
import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.enums.ClassDocumentTypeEnums;
import com.mxdx.edu.enums.CreateTypeEnums;
import com.mxdx.edu.enums.DisplayTypeEnums;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.model.StlistInfo;
import com.mxdx.edu.service.IStudentTuitionService;
import com.mxdx.edu.util.DictUtils;
import com.mxdx.edu.util.ServletUtil;

/**
 * 在校生controller
 * @author lihy
 */
@Controller
@RequestMapping(value = "/internal")
public class InternalStudentController extends BaseController{

    private AppLogger logger = new AppLogger(InternalStudentController.class);

    @Resource
    private IStudentTuitionService studentTuitionService;
    
	@Resource
	private IFileUploadServiceFacade fileUploadServiceFacade;

    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/myClass")
    public ModelAndView myClass(HttpServletRequest request){
        logger.entry(ServletUtil.getClientIp(request), "myClass");
        ApiResult<String> apiResult = new ApiResult<>();
        ModelAndView result = new ModelAndView("/h5/wodebanji");
        Map<String, Object> semesterMap = null;
        List<Map<String, Object>> schoolmateList = null;
        String mood="";
        String studentName = "";
        String headPortrait = "";
        List<Map<String, Object>> classBulletinList = null;
        List<Map<String, Object>> teacherWordsList = null;
        Map<String, Object> headTeacherWords = null;
        Map<String,Object> studentTuitionMap = new HashMap<>();
        Map<String,Object> findClassFeeMap = new HashMap<>();
        try{
            String token = sessionUtil.getTokenSession(request);
            Map<String, Object> map = (Map<String, Object>) redisUtil.get(token);
            String studentId = CommonUtils.getStrValueFromMap(map, "studentId", "");
            mood = CommonUtils.getStrValueFromMap(map, "mood", "");
            studentName = CommonUtils.getStrValueFromMap(map, "studentName", "");
            headPortrait = CommonUtils.getStrValueFromMap(map, "headPortrait", "");
            Map<String, Object> param = new HashMap<>();
            param.put("studentId", studentId);
            Map<String, Object> studentMap = studentService.findStudentMapOneByMap(param);
            studentTuitionMap = studentTuitionService.findStudentTuition(param);

            String classId = CommonUtils.getStrValueFromMap(studentMap, "classId", "");
            param.put("classId", classId);
            findClassFeeMap = studentTuitionService.findClassFee(param);
            semesterMap = schoolStatusService.findSchoolMapByMap(param);
            if(semesterMap!=null){
                String level =  CommonUtils.getStrValueFromMap(semesterMap,"level","");
                semesterMap.put("levelName", DictUtils.getDictLabel(level,"level",""));
            }

            Map<String, Object> findClassMap = new HashMap<>();
            int num = 0;
            findClassMap.put("begin", num);
            //我的同学
            findClassMap.put("myStudentId", studentId);
            findClassMap.put("classId", classId);
            findClassMap.put("begin", num);
            schoolmateList = studentService.findSchoolmateByMap(findClassMap);

            //班级公告
//            findClassMap.put("classId", classId);
            findClassMap.put("documentType", ClassDocumentTypeEnums.CLASS_BULLETIN.getCode());
            findClassMap.put("displayType", DisplayTypeEnums.TEXT.getCode());
            classBulletinList = classDocumentService.findListByMap(findClassMap);
            //班主任的话
            findClassMap.put("documentType", ClassDocumentTypeEnums.HEAD_TEACHER_WORDS.getCode());
            findClassMap.put("displayType", DisplayTypeEnums.TEXT.getCode());
            //teacherWordsList = classDocumentService.findListByMap(findClassMap);
            //班主任的话header
            findClassMap.put("displayType", DisplayTypeEnums.IMAGE.getCode());
            headTeacherWords = classDocumentService.findMapByMap(findClassMap);
            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        result.addObject("schoolStatus", semesterMap);
        result.addObject("schoolmateList", schoolmateList);
        result.addObject("mood", mood);
        result.addObject("studentName", studentName);
        result.addObject("headPortrait", headPortrait);
        result.addObject("imageHost", imageHost);
        result.addObject("classBulletinList", classBulletinList);
        //result.addObject("teacherWordsList", teacherWordsList);
        result.addObject("headTeacherWords", headTeacherWords);
        result.addObject("studentTuition", studentTuitionMap);
        result.addObject("classFee", findClassFeeMap);

        return result;
    }

    /**
     * 获取我的好友列表
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/myFrids")
    @ResponseBody
    public ApiResult<List<Map<String, Object>>> myFriends(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "myFrids");
        ApiResult<List<Map<String, Object>>> apiResult = new ApiResult<>();
        List<Map<String, Object>> FriendsMapList = null;
        Map<String,Object> findMap = new HashMap<>();
        try{
            //我的好友
            String studentId = ServletUtil.getParameterStr(request, "stuId", "");
            findMap.put("studentId", studentId);
            findMap.put("pasFlag","1");
            FriendsMapList = studentService.findFriendsByMap(findMap);
            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        //result.addObject("schoolStatus", semesterMap);
        //result.addObject("schoolmateList", schoolmateList);
        apiResult.setResult(FriendsMapList);
        //result.setResult(resultMap);
        return apiResult;
    }



    /**
     * 搜索添加好友信息
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/mySfrid")
    @ResponseBody
    public ApiResult<Map<String, Object>> mySfrid(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "mySfrid");
        ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
        List<Map<String, Object>> SfridMapList = null;
        Map<String,Object> findMap = new HashMap<>();
        Map<String,Object> resultMap=new HashMap<>();
        try{
            //我的好友
            String phoneNumber = ServletUtil.getParameterStr(request, "phoneNumber", "");
            findMap.put("phoneNumber", phoneNumber);
            Map<String,Object> userInfo=studentService.findStudentMapOneByMap(findMap);
            resultMap.put("userInfo", userInfo);
            SfridMapList = studentService.findSfridByMap(findMap);
            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        //result.addObject("schoolStatus", semesterMap);
        //result.addObject("schoolmateList", schoolmateList);
         resultMap.put("resultList",SfridMapList);
         apiResult.setResult(resultMap);
        return apiResult;
    }
    /**
     * 添加好友保存请求信息
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/myAfrid")
    @ResponseBody
    public ApiResult<String> myAfrid(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "myAfrid");
        ApiResult<String> apiResult = new ApiResult<>();
        //List<Map<String, Object>> NfridMapList = null;
        String studentId = ServletUtil.getParameterStr(request,	"studentId", "");// 我的id
        String studentTk = ServletUtil.getParameterStr(request,	"studentTk", "");// Rong tk
        String studentFd = ServletUtil.getParameterStr(request, "studentFd", "");// 好友ID
        String studentFk = ServletUtil.getParameterStr(request, "studentFk", "");// 好友tk
        String addNote = ServletUtil.getParameterStr(request, "AddNote", "");// 好友备注
        //String password = ServletUtil.getParameterStr(request, "password", "");// 用户密码

        Map<String,Object> findMap = new HashMap<>();
        try{
        	//判断两人是否已经是好友关系或者已经发起申请
        	findMap.put("studentId", studentId);
        	findMap.put("studentFd", studentFd);
        	List<Map<String,Object>>  relationList= studentService.findFriendsByMap(findMap);
        	if(relationList!=null && !relationList.isEmpty()){
        		apiResult.setMessage("已经是好友或者已经申请好友！");
        		apiResult.setResult("1");
        		return apiResult;
        	}
            StlistInfo stlistInfo = new StlistInfo();
            String Id = serialService.generateSerialNum(
                    CreateTypeEnums.CREATE_STUDENT.getCode(), 7);
            stlistInfo.setId(Id);
            stlistInfo.setStudentId(studentId);
            stlistInfo.setStudentTk(studentTk);
            stlistInfo.setStudentFd(studentFd);
            stlistInfo.setStudentFk(studentFk);
            stlistInfo.setAddNote(addNote);
            studentService.saveStlist(stlistInfo);
            apiResult.setResult("0");
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        //result.addObject("schoolStatus", semesterMap);
        //result.addObject("schoolmateList", schoolmateList);
        //apiResult.setResult(JSONObject.toJSONString(NfridMapList));
        //result.setResult(resultMap);
        return apiResult;
    }

    /**
     * 搜索添加好友信息
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/myNfrid")
    @ResponseBody
    public ApiResult<List<Map<String, Object>>> myNfrid(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "myNfrid");
        ApiResult<List<Map<String, Object>>> apiResult = new ApiResult<>();
        List<Map<String, Object>> NfridMapList = null;
        Map<String,Object> findMap = new HashMap<>();
        try{
            //我的好友
            String studentId = ServletUtil.getParameterStr(request, "studentId", "");
            findMap.put("studentFd", studentId);
            NfridMapList = studentService.findNfridByMap(findMap);
            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        //result.addObject("schoolStatus", semesterMap);
        //result.addObject("schoolmateList", schoolmateList);
        apiResult.setResult(NfridMapList);
        //result.setResult(resultMap);
        return apiResult;
    }

    /**
     * 同意添加好友信息
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/myPfrid")
    @ResponseBody
    public ApiResult<String> myPfrid(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "myPfrid");
        ApiResult<String> apiResult = new ApiResult<>();

        String studentFd = ServletUtil.getParameterStr(request,	"studentId", "");// 我的id
        //String studentTk = ServletUtil.getParameterStr(request,	"studentTk", "");// Rong tk
        String studentId = ServletUtil.getParameterStr(request, "studentFd", "");// 好友ID
        //String studentFk = ServletUtil.getParameterStr(request, "studentFk", "");// 好友tk
        //String addNote = ServletUtil.getParameterStr(request, "AddNote", "");// 好友备注
        try{
            Map<String, Object> param = new HashMap<>();
            param.put("studentId", studentId);
            param.put("studentFd", studentFd);
            param.put("passFlag", "1");
            //param.put("studentId", studentId);
            //param.put("studentFd", studentFd);
            studentService.updateSlistByMap(param);
            apiResult.setInfo("成功！");
        } catch (Exception e) {
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);

        }
        return apiResult;
    }
    
  
    
    @RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> handleUploadProcess(HttpServletRequest request) {
		logger.entry(request.getRemoteHost(), "uploadPic");
		Map<String, Object> logMap = new HashMap<>();
		Map<String, Object> returnMap = new HashMap<>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String fileName = "";
		try {
			for (Iterator<?> it = multipartRequest.getFileNames(); it.hasNext();) {
				String key = (String) it.next();
				List<MultipartFile> mulfiles = multipartRequest.getFiles(key); // 一个上传控件上传多张图片
				for (MultipartFile file : mulfiles) {
					if (file.getSize() == 0) {
						returnMap.put("msg", "请选择上传文件");
						return returnMap;
					}
					String name = file.getOriginalFilename();
					String suffix = name.substring(name.lastIndexOf(".") + 1,
							name.length());
					logMap.put("name", name);
					logMap.put("suffix", suffix);
					ApiResult<Map<String, String>> ret = fileUploadServiceFacade
							.saveFile("mxdx", suffix, file.getInputStream());
					String status = ret.getStatus();
					logMap.put("status", status);
					logger.doInfo("上传文件结果", ret);
					if ("00000000".equals(status)) {
						fileName = ret.getResult().get("saveFilename");
					}
				}
			}
			returnMap.put("msg", "success");
			returnMap.put("fileName", fileName);
			returnMap.put("imageUrl",
					String.format("%s%s", imageHost, fileName));

			logMap.putAll(returnMap);
			logger.info(logMap);

			return returnMap;
		} catch (Exception e) {
			e.printStackTrace();
			returnMap.put("msg", "failed");
			logMap.putAll(returnMap);
			logger.error(logMap);
			return returnMap;
		}
	}
    
    
    
    /**
     * 发布学习圈信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/app/myAcirls",method = RequestMethod.POST)
    @ResponseBody
	public ApiResult<List<Map<String, Object>>> myAcirls(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "myAcirls");
		ApiResult<List<Map<String, Object>>> apiResult = new ApiResult<>();
		Map<String, Object> findMap = new HashMap<>();
		try {
			String studentId = ServletUtil.getParameterStr(request, "stuId", "");
			String messa = ServletUtil.getParameterStr(request, "messa", "");
			findMap.put("studentId", studentId);
			System.out.println("---------------"+messa);
			findMap.put("messa", messa);
			String id=serialService.generateSerialNum(CreateTypeEnums.CREATE_CIRCLE.getCode(), 8); 
			findMap.put("id", id);
			findMap.put("cdate", new Date());
 			String fileName = "";
		 	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			for (Iterator<?> it = multipartRequest.getFileNames(); it.hasNext();) {
				String key = (String) it.next();
				List<MultipartFile> mulfiles = multipartRequest.getFiles(key); // 一个上传控件上传多张图片
				for (MultipartFile file : mulfiles) {
					if (file.getSize() == 0) {
						apiResult.setMessage("请选择上传文件");
						return apiResult;
					}
					String name = file.getOriginalFilename();
					String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
					ApiResult<Map<String, String>> ret = fileUploadServiceFacade.saveFile("mxdx", suffix,
							file.getInputStream());
					String status = ret.getStatus();
					if ("00000000".equals(status)) {
						fileName = ret.getResult().get("saveFilename");
					}
				}
			} 
 			findMap.put("pictu", String.format("%s%s", imageHost, fileName));
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		boolean result=studentService.saveCirls(findMap);
		if(result){
			apiResult.setInfo("发布成功！");
		}else{
			apiResult.setMessage("fail!");
		}
		return apiResult;
	}
    
    
    
    @RequestMapping(value = "/app/myAcomnt")
    @ResponseBody
	public ApiResult<List<Map<String, Object>>> myAcomnt(HttpServletRequest request) {
    	logger.entry(ServletUtil.getClientIp(request), "myAcomment");
		ApiResult<List<Map<String, Object>>> apiResult = new ApiResult<>();
		Map<String, Object> findMap = new HashMap<>();
		String id=serialService.generateSerialNum(
                CreateTypeEnums.CREATE_CIRCLE.getCode(), 9); 
		String studentId = ServletUtil.getParameterStr(request, "stuId", "");
		String comsg = ServletUtil.getParameterStr(request, "comsg", "");
		String infid = ServletUtil.getParameterStr(request, "infid", "");
		String parentId = ServletUtil.getParameterStr(request, "parId", "");
		
		findMap.put("id", id);
		findMap.put("studentId", studentId);
		findMap.put("comsg", comsg);
		findMap.put("infid", infid);
		findMap.put("parentId", parentId==null?"0":parentId);
		findMap.put("dflag", "0");
		boolean result=studentService.saveComment(findMap);
		if(result){
			apiResult.setInfo("发布成功！");
		}else{
			apiResult.setMessage("fail!");
		}
		return apiResult;
		
    }
    
    
    /**
     * 获取我的学习圈
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/myFcirls")
    @ResponseBody
    public ApiResult<List<Map<String, Object>>> myFcirls(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "myFcirls");
        ApiResult<List<Map<String, Object>>> apiResult = new ApiResult<>();
        List<Map<String, Object>> FcirlsMapList = null;
        Map<String,Object> findMap = new HashMap<>();
        try{
            //我的
            String stuId = ServletUtil.getParameterStr(request, "stuId", "");
            findMap.put("studentId", stuId);
            FcirlsMapList = studentService.findFcirlsByMap(findMap);

            List<Map<String, Object>> CommsMapList = null;

            for(Map<String, Object> cml:FcirlsMapList){
                String cirlsId=String.valueOf(cml.get("id"));
                findMap.put("cirlsId",cirlsId);
                CommsMapList= studentService.findCirlsComment(findMap);
                cml.put("comments",CommsMapList);
            }

            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        //result.addObject("schoolStatus", semesterMap);
        //result.addObject("schoolmateList", schoolmateList);
        apiResult.setResult(FcirlsMapList);
        //result.setResult(resultMap);
        return apiResult;
    }
    /**
     * 获取我的学习圈
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/app/myCirls")
    @ResponseBody
    public ApiResult<List<Map<String, Object>>> myCirls(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "myCirls");
        ApiResult<List<Map<String, Object>>> apiResult = new ApiResult<>();
        List<Map<String, Object>> CirlsMapList = null;
        Map<String,Object> findMap = new HashMap<>();
        try{
            //我的
            String stuId = ServletUtil.getParameterStr(request, "stuId", "");
            findMap.put("studentId", stuId);
            CirlsMapList = studentService.findCirlsByMap(findMap);

            List<Map<String, Object>> CommsMapList = null;

            for(Map<String, Object> cml:CirlsMapList){
                String cirlsId=String.valueOf(cml.get("id"));
                findMap.put("cirlsId",cirlsId);
                CommsMapList= studentService.findCirlsComment(findMap);
                cml.put("comments",CommsMapList);
            }
            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        //result.addObject("schoolStatus", semesterMap);
        //result.addObject("schoolmateList", schoolmateList);
        apiResult.setResult(CirlsMapList);
        //result.setResult(resultMap);
        return apiResult;
    }
    /**
	 * 获取更多好友信息
	 * @param request
	 * @return
	 */
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/moreNews")
	@ResponseBody
	public ApiResult<String> moreNews(HttpServletRequest request){
		logger.entry(ServletUtil.getClientIp(request), "moreNews");
		ApiResult<String> apiResult = new ApiResult<>();
		String num = ServletUtil.getParameterStr(request, "num", "1");
		String sign = ServletUtil.getParameterStr(request, "sign", "");
		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> studentMap = (Map<String, Object>) redisUtil.get(token);
		String classId = CommonUtils.getStrValueFromMap(studentMap, "classId", "");
		String studentId = CommonUtils.getStrValueFromMap(studentMap, "studentId", "");
		Map<String, Object> findClassMap = new HashMap<>();
        int currentPage = Integer.valueOf(num);
        findClassMap.put("begin", (currentPage-1)*4);
        //班级公告
        findClassMap.put("classId", classId);
        List<Map<String, Object>> classBulletinList = null;
        if(ClassDocumentTypeEnums.CLASS_BULLETIN.getDesc().equals(sign)){
            findClassMap.put("documentType", ClassDocumentTypeEnums.CLASS_BULLETIN.getCode());
            findClassMap.put("displayType", DisplayTypeEnums.TEXT.getCode());
            classBulletinList = classDocumentService.findListByMap(findClassMap);
        }else if(ClassDocumentTypeEnums.HEAD_TEACHER_WORDS.getDesc().equals(sign)){
            findClassMap.put("documentType", ClassDocumentTypeEnums.HEAD_TEACHER_WORDS.getCode());
            findClassMap.put("displayType", DisplayTypeEnums.TEXT.getCode());
            classBulletinList = classDocumentService.findListByMap(findClassMap);
        }else if(ClassDocumentTypeEnums.MY_CLASSMATES.getDesc().equals(sign)){
            findClassMap.put("myStudentId", studentId);
            classBulletinList = studentService.findSchoolmateByMap(findClassMap);
        }
        apiResult.setResult(JSONObject.toJSONString(classBulletinList));
        apiResult.setInfo(sign);
		return apiResult;
	}
    
//	ApiResult<String> apiResult = new ApiResult<>();
//	String sign = ServletUtil.getParameterStr(request, "sign", "");
//	String num = ServletUtil.getParameterStr(request, "num", "1");
//	String parentId = ServletUtil.getParameterStr(request, "parentId", "0");
//	
//	int currentPage = Integer.parseInt(num);
//	Map<String, Object> param = new HashMap<>();
//	param.put("parentId", parentId);
//	param.put("begin", (currentPage-1)*4);
//	param.put("endNum", 4);
//	param.put("name", sign);
//	param.put("displayType", DisplayTypeEnums.TEXT.getCode());
//	if(sign.equals(CmsIdEnums.OUTSTANDING_STUDENTS.getDesc()) || sign.equals(CmsIdEnums.STUDENT_UNION.getDesc())){
//		param.put("begin", (currentPage-1)*3);
//		param.put("endNum", 3);
//		param.put("displayType", DisplayTypeEnums.IMAGE.getCode());
//	}
//	//新闻中心
//	List<Map<String, Object>> newsList = cmsCategoryService.findListByMap(param);
//	apiResult.setResult(JSONObject.toJSONString(newsList));
//	apiResult.setInfo(imageHost);
	
    @RequestMapping(value = "/auth/source")
    public ModelAndView course(){

        return null;
    }
}
